package cn.kvchoi.proactor_aio.server.handlers;

import cn.kvchoi.proactor_aio.server.SessionStateAttachment;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, SessionStateAttachment> {

    private final AsynchronousServerSocketChannel listener;

    public AcceptCompletionHandler(AsynchronousServerSocketChannel listener) {
        this.listener = listener;
    }

    @Override
    public void completed(AsynchronousSocketChannel socketChannel, SessionStateAttachment sessionStateAttachment) {

        System.out.println("Accept Handler running on " + Thread.currentThread().getName());
        // accept the next connection
        SessionStateAttachment attachment = new SessionStateAttachment();
        listener.accept(attachment, this);

        // handle this connection
        ByteBuffer inputBuffer = ByteBuffer.allocate(2048);
        ReadCompletionHandler readCompletionHandler = new ReadCompletionHandler(socketChannel, inputBuffer);
        socketChannel.read(inputBuffer, sessionStateAttachment, readCompletionHandler);
    }

    @Override
    public void failed(Throwable exc, SessionStateAttachment sessionStateAttachment) {
        // Handle connection failure...
    }

}